package com.mdd.front.service.teacher.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.entity.course.Course;
import com.mdd.common.entity.course.CourseCatalogue;
import com.mdd.common.entity.teacher.Teacher;
import com.mdd.common.mapper.course.CourseCatalogueMapper;
import com.mdd.common.mapper.course.CourseMapper;
import com.mdd.common.mapper.course.StudyCourseCatalogueMapper;
import com.mdd.common.mapper.teacher.TeacherMapper;
import com.mdd.common.utils.UrlUtil;
import com.mdd.front.service.teacher.ITeacherService;
import com.mdd.front.vo.course.CourseListVo;
import com.mdd.front.vo.teacher.TeacherDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 讲师实现类
 * @author panweiliang
 */
@Service
public class TeacherServiceImpl implements ITeacherService {
        
    @Resource
    TeacherMapper teacherMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    CourseCatalogueMapper courseCatalogueMapper;



    /**
     * 讲师详情
     *
     * @author panweiliang
     * @param id 主键参数
     * @return Teacher
     */
    @Override
    public TeacherDetailVo detail(Integer id, Integer userId) {

        NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用
        percent.setMaximumFractionDigits(3); //百分比小数点最多3位
        Teacher model = teacherMapper.selectOne(
                new QueryWrapper<Teacher>()
                    .eq("id", id)
                        .eq("status", "1")
                            .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TeacherDetailVo vo = new TeacherDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setAvatar(UrlUtil.toAbsoluteUrl(model.getAvatar()));

        MPJQueryWrapper<Course> mpjCourseQueryWrapper = new MPJQueryWrapper<Course>()
                .selectAll(Course.class)
                .select("COUNT(catalogue.id) as catalogueCount, IFNULL(sc.status, 1) AS learnState")
                .leftJoin("?_course_catalogue catalogue ON catalogue.course_id = t.id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .leftJoin("?_study_course sc ON sc.course_id = t.id AND sc.delete_time IS NULL ".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe) + "AND sc.user_id = " + userId)
//                .eq("sc.user_id", userId)
                .eq("t.teacher_id", id)
//                .eq("t.status", "1")
                .groupBy("t.id");
        List<CourseListVo> courses = courseMapper.selectJoinList(CourseListVo.class, mpjCourseQueryWrapper);
        for(CourseListVo item : courses) {
            int type = item.getType() != null ? item.getType() : 0;
            if (type == 1 || type == 2 || type == 3) {
                int feeType = item.getFeeType() != null ? item.getFeeType() : 0;

                //还需要获取最后一次学习的课程目录
                MPJQueryWrapper<CourseCatalogue> courseCatalogueQueryWrapper = new MPJQueryWrapper<CourseCatalogue>()
                        .selectAll(CourseCatalogue.class)
                        .innerJoin("?_study_course_catalogue scc ON scc.catalogue_id = t.id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                        .eq("t.status", "1")
                        .eq("scc.user_id", userId)
                        .eq("scc.course_id", item.getId())
                        .orderByDesc(Arrays.asList("scc.create_time"));

                List<CourseCatalogue> courseCatalogues = courseCatalogueMapper.selectJoinList(CourseCatalogue.class, courseCatalogueQueryWrapper);

                if (courseCatalogues == null || courseCatalogues.size() == 0) {
                    courseCatalogues = courseCatalogueMapper.selectList(new QueryWrapper<CourseCatalogue>()
                            .eq("course_id", item.getId())
                            .eq("status", "1").orderByAsc(Arrays.asList("sort", "id")));
                }

                item.setStudyCatalogues(courseCatalogues);

                BigDecimal catalogueCount = new BigDecimal(String.valueOf(item.getCatalogueCount()));
                BigDecimal studyCatalogueCount = new BigDecimal(String.valueOf(courseCatalogues.size()));

                if (studyCatalogueCount.doubleValue() != 0 && catalogueCount.doubleValue() != 0) {
                    BigDecimal studyRate = studyCatalogueCount.divide(catalogueCount, 2, BigDecimal.ROUND_DOWN);
                    item.setStudyRate(percent.format(studyRate));
                } else {
                    item.setStudyRate(percent.format(new BigDecimal("0")));
                }
            }

            item.setCover(UrlUtil.toAbsoluteUrl(item.getCover()));
        }
        vo.setCourses(courses);
        return vo;
    }



}
